package org.lboot.rbac.provider;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Validator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lboot.core.auth.AuthService;
import org.lboot.rbac.constant.RbacAuthConst;
import org.lboot.rbac.module.role.SysRoleService;
import org.lboot.rbac.module.user.SysUserService;
import org.lboot.starter.redis.RedisCache;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author kindear
 * AuthService lucy-rbac 拓展实现
 */
@Slf4j
@Service
@AllArgsConstructor
public class RbacAuthServiceImpl implements AuthService {

    SysRoleService roleService;

    SysUserService userService;

    RedisCache redisCache;


    // 获取当前登录ID
    @Override
    public String getUid() {
        return StpUtil.getLoginIdAsString();
    }

    @Override
    public String getToken() {
        return StpUtil.getTokenValue();
    }

    @Override
    public Boolean doLogin(String id) {
        StpUtil.login(id);
        return true;
    }

    @Override
    public Boolean doLogout(String id) {
        if (Validator.isEmpty(id)){
            StpUtil.logout();;
        }else {
            StpUtil.logout(id);
        }
        return true;
    }

    @Override
    public Boolean isLogin() {
        return StpUtil.isLogin();
    }

    @Override
    public Boolean isAdmin() {
        // 未登录判断
        if (!isLogin()) return false;
        // 角色
        List<String> roles = getRoles();
        if (roles.contains("admin")){
            return true;
        }
        return false;
    }

    @Override
    public List<String> getRoles() {
        return StpUtil.getRoleList();
//        Long userId = StpUtil.getLoginIdAsLong();
//        Set<SysRole> roles = new HashSet<>(userService.getRoles(userId));
//        List<String> roleKeys = new ArrayList<>();
//        for (SysRole role:roles){
//            roleKeys.add(role.getRoleKey());
//        }
//        return roleKeys;
    }

    @Override
    public List<String> getPerms() {
        return StpUtil.getPermissionList();
//        Long userId = StpUtil.getLoginIdAsLong();
//        Set<SysRole> roles = new HashSet<>(userService.getRoles(userId));
//        List<String> perms = new ArrayList<>();
//        for (SysRole role:roles){
//            perms.addAll(role.getPermissions());
//        }
//        return perms;
    }

    @Override
    public void doBan(Object id, Integer hour) {
        // 踢人
        StpUtil.kickout(id);
        // 设置禁止时长
        redisCache.setCacheObject(RbacAuthConst.BAN_CODE.concat(id.toString()),1,hour, TimeUnit.HOURS);
    }

    @Override
    public Boolean isBan(Object id) {
        Object isBan = redisCache.getCacheObject(RbacAuthConst.BAN_CODE.concat(id.toString()));
        return Validator.isNotEmpty(isBan);
    }



}
